package com.algernoon.nettydemo.netty3.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketServer {
	
	public void bind(int port) throws InterruptedException {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						// 请求或应答消息编码或解码为http消息
						ch.pipeline().addLast("http-codec", new HttpServerCodec());
						// 将http消息的多个部分组合成一个完整的http消息
						ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
						// 向客户端发送html5文件，主要用于支持浏览器和客户端进行WebSocket通信
						ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
						ch.pipeline().addLast("handler", new WebSocketServerHandler());
					}
				});
			
			Channel channel = b.bind(port).sync().channel();
			
			System.out.println("websocket server started at port: " + port);
			
			System.err.println("http://localhost:" + port + "/");
			
			channel.closeFuture().sync();
			
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		new WebSocketServer().bind(8080);
	}

}
